﻿using System;
using System.ComponentModel.Composition;
using System.Data.SqlClient;
using System.Linq;
using Security.Connect;
using Security.Connect.ViewModels;
using Security.Connect.Views;
using Security.Events.Commands;
using Security.Helpers;

namespace Security.Events.Handlers
{
    [Export(typeof(CommandHandler))]
    class ShowConnectionViewCommandHandler : CommandHandler
    {
        private readonly IConnectionContainer connectionContainer;

        [ImportingConstructor]
        public ShowConnectionViewCommandHandler(EventBroker eventBroker, IConnectionContainer connectionContainer) : 
            base(eventBroker)
        {
            this.connectionContainer = connectionContainer;
        }

        protected override void Subscribe()
        {
            eventBroker.OfType<ShowConnectionViewCommand>().Subscribe(OnShowConnectionView);
        }

        private void OnShowConnectionView(ShowConnectionViewCommand command)
        {
            var viewModel = new ConnectionViewModel();
            var view = new ConnectionView(viewModel);
            bool? dialogResult = view.ShowDialog();
            connectionContainer.Connection.ConnectionString = viewModel.ConnectionString;
            command.DialogResult = dialogResult.HasValue && dialogResult.Value;
        }
    }
}
